package com.hxtec.polaris.service.impl;

import com.hxtec.polaris.commons.contants.CommonContants;
import com.hxtec.polaris.entity.ShopCartItem;
import com.hxtec.polaris.entity.ShopProductBase;
import com.hxtec.polaris.entity.ShopProductVariant;
import com.hxtec.polaris.entity.ShopProductVariantAttrValue;
import com.hxtec.polaris.entity.ShopStock;
import com.hxtec.polaris.entity.ShopUser;
import com.hxtec.polaris.mapper.ShopCartItemMapper;
import com.hxtec.polaris.service.CartItemService;
import com.hxtec.polaris.service.ProductService;
import com.hxtec.polaris.service.StockService;
import com.hxtec.polaris.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;


/**
 * @author Caps
 * @date 2019/11/25
 */
@Service
public class CartItemServiceImpl implements CartItemService {

    @Resource
    private ShopCartItemMapper cartItemMapper;

    @Resource
    private ProductService productService;


    @Resource
    private UserService userService;

    @Resource
    private StockService stockService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> addTocart(int sku, int quantity) {
//        String phone = this.getUser();
        String phone="12345678900";
        Map<String,Object> map=new HashMap<>();
        //未登录
        if(StringUtils.equals("anonymousUser",phone)){
            map.put(CommonContants.STATUS,"error");
            map.put(CommonContants.MESSAGE,"userError");
            return map;
        }
        ShopProductVariant skuInfo = productService.getSkuProductBySku(sku);
        ShopProductBase spuInfo=productService.getSpuInfoBySpu(skuInfo.getSpu());
        List<ShopProductVariantAttrValue> skuSaleAttrValueBySku = productService.getSkuSaleAttrValueBySku(sku);
        StringBuilder skuSaleAttr= new StringBuilder();
        for (ShopProductVariantAttrValue variantAttrValue : skuSaleAttrValueBySku) {
            String skuSale = variantAttrValue.getSaleAttrName() +":"+ variantAttrValue.getSaleAttrValueName() + "|";
            skuSaleAttr.append(skuSale);
        }
        String substring = skuSaleAttr.substring(0, skuSaleAttr.length() - 1);
        ShopCartItem cartItem= ShopCartItem.builder()
                .quantity(quantity)
                .createTime(new Date())
                .updateTime(new Date())
                .deleteStatus("N")
                .productCategoryId(spuInfo.getCategoryId())
                .productId(skuInfo.getSpu())
                .productName(skuInfo.getSkuName())
                .productSkuId(skuInfo.getSku())
                .productPic(skuInfo.getImage())
                .productSubTitle(skuInfo.getDescription())
                .price(skuInfo.getPrice())
                .discountprice(skuInfo.getDiscountPrice())
                .productAttr(substring).build();

        ShopStock stockInfo = stockService.getStockInfoBuSku(skuInfo.getSku());
        cartItem.setStock(stockInfo.getAvailable());

        ShopUser userInfo=userService.getUserInfoByPhone(phone);

        ShopCartItem shopCartItem=this.ifCartExistByUser(userInfo.getId(),sku);
        Integer i;
        if(null ==shopCartItem){
            //沒有加过
            cartItem.setMemberId(userInfo.getId());
            cartItem.setMemberNickname(userInfo.getNickname());
            i=this.insertTocart(cartItem);
        }
        else {
            shopCartItem.setQuantity(shopCartItem.getQuantity()+quantity);
            i=this.updateCart(shopCartItem);
        }
        map.put("cartId",i);
        return map;
    }

    /**
     * 获取购物车列表
     * @return
     */
    @Override
    public List<ShopCartItem> getCartList() {
/*
        String phone = this.getUser();
*/
        String phone="12345678900";
        List<ShopCartItem> cartList=new ArrayList<>();
        if(!StringUtils.equals("anonymousUser",phone)){
            ShopUser userInfo=userService.getUserInfoByPhone(phone);
            Example example=new Example(ShopCartItem.class);
            example.createCriteria().andEqualTo("memberId",userInfo.getId())
                                    .andEqualTo("deleteStatus","N");
            cartList = cartItemMapper.selectByExample(example);
        }
        return cartList;
    }


    @Override
    public void delCart(String cartId, String memberId) {
        Example example=new Example(ShopCartItem.class);
        example.createCriteria().andEqualTo("id",cartId)
                .andEqualTo("memberId",memberId);
        cartItemMapper.deleteByExample(example);
    }

    @Override
    public Map<String, Object> deleteCart(String ids) {
        String phone="12345678900";
        String memberId="6";
        Map<String,Object> map=new HashMap<>();
        //未登录
        if(StringUtils.equals("anonymousUser",phone)){
            map.put(CommonContants.STATUS,"error");
            map.put(CommonContants.MESSAGE,"userError");
            return map;
        }
        String[] cartIds=ids.split(",");
        List<String> idList = Arrays.asList(cartIds);
        idList.forEach(id->{
            this.delCart(id, memberId);
        });
        map.put(CommonContants.STATUS,"success");
        return map;
    }

    @Override
    public List<ShopCartItem> getCartCheckedGoods(String cartIdData) {
        String[] cartIdDatas =cartIdData.split(",");
        List<String> cartIdList = Arrays.asList(cartIdDatas);
        List<ShopCartItem> shopCartItemList=new ArrayList<>();
        cartIdList.forEach(id->{
            ShopCartItem shopCartItem = cartItemMapper.selectByPrimaryKey(id);
            shopCartItemList.add(shopCartItem);
        });
        return shopCartItemList;
    }

    @Override
    public void delCartById(List<Integer> cartIds) {
        cartIds.forEach(id->{
            cartItemMapper.deleteByPrimaryKey(id);
        });
    }


    private String getUser(){
        return SecurityContextHolder.getContext().getAuthentication().getName();
    }

    @Override
    public int insertTocart(ShopCartItem cartItem) {
        if (StringUtils.isNotEmpty(String.valueOf(cartItem.getMemberId()))) {
            cartItemMapper.insert(cartItem);
            return cartItem.getId();
        }
        return 0;
    }


    @Override
    public ShopCartItem ifCartExistByUser(Integer memberId, Integer sku) {
        ShopCartItem cartItem=new ShopCartItem();
        cartItem.setMemberId(memberId);
        cartItem.setProductSkuId(sku);
        return cartItemMapper.selectOne(cartItem);
    }

    @Override
    public int updateCart(ShopCartItem cartItem) {
        Example example=new Example(ShopCartItem.class);
        example.createCriteria().andEqualTo("id",cartItem.getId());
        cartItemMapper.updateByExampleSelective(cartItem, example);
        return cartItem.getId();
    }


    /**
     * 当前购物车数据库是否存在
     * @param shopCartItems
     * @param cartItem
     * @return
     */
    private boolean if_cart_exist(List<ShopCartItem> shopCartItems, ShopCartItem cartItem) {
        boolean flag = false;
        for (ShopCartItem shopCartItem : shopCartItems) {
            Integer productSkuId = shopCartItem.getProductSkuId();

            if (productSkuId.equals(cartItem.getProductSkuId())) {
                flag = true;
            }
        }
        return flag;
    }
}
